#include <stdio.h>
#include <stdlib.h>

#define INIT_SIZE 5
#define INCREMENT 3

typedef struct {
    int *base; //栈底
    int *top;  //栈顶
    int size;  //容量
} stack;

stack init() { //初始化栈
    stack S;
    S.base = malloc(sizeof(int) * INIT_SIZE);
    if (S.base == NULL)
        exit(!0);
    // 1.初始化top
    S.top = S.base;
    // 2.初始化size
    S.size = INIT_SIZE;
    return S;
}

int length(stack* S) { //计算元素个数
    if (S->base == NULL)
        return -1;

    return *S->top - *S->base;    // 3.返回栈内元素个数
}

void push(stack* S, int e) { //压栈
    if (length(S) >= S->size) {
        S->base = realloc(S->base, sizeof(int) * (S->size + INCREMENT));
        if (!S->base)
            exit(!0);
        // 4.调整top
        S->top++;
        // 5.调整size
        S->size = INIT_SIZE - 1;
    }
    // 6.压入e
    S->top = e;
}

stack pop(stack S, int *pe) { //弹栈
    if (S.base == S.top)/*// 7.栈为空*/
            exit(!0);
    // 8.调整top并弹出栈顶给pe
    S.top--;
    S.top = pe;
    return S;
}

int main(int argc, char const *argv[]) {
    stack S = init();
    push(&S, 1);
    push(&S, 2);
    push(&S, 3);
    push(&S, 4);
    push(&S, 5);
    push(&S, 6);
    int e = -1;
    S = pop(S, &e);
    printf("pop: %d\n", e);
    printf("length: %d\n", length(&S));

    S = pop(S, &e);
    printf("pop: %d\n", e);
    printf("length: %d\n", length(&S));

    printf("size: %d\n", S.size);

    return 0;
}
